<?php
echo $this->headScript()->setFile($this->baseUrl().'/js/jquery/tree/javascripts/jquery.treeTable.js');
echo $this->headScript()->setFile($this->baseUrl().'/js/jquery/table-sorter/jquery.dataTables.js');
?>

<script type="text/javascript">
$(document).ready(function() {
	 categoryTreeGen();
	 imageThumbnil();
	 		
	$('a.close_dialog_btn').click(function() {		 
		$("#upload-form").dialog('option','hide','explode').dialog('close');			
	});
	
	$('a.reset_btn').click(function() {			
		 resetFields();	
		 imageThumbnil();	
	});
	
});

function removeError()
{
	$('#putContent').html('');		
}


function addError(key,errMsg)
{
	var err_id = key+'_err';
	var field_name = key;
	$('#'+field_name).addClass('ui-state-error');
	$('#'+err_id).append(errMsg);
}

function openLoaderDialog()
{
	$('#dialog_container').dialog({
				autoOpen: true,
				modal: true,
				show: 'fade',
				resizable: 'false',				
				open: function(event, ui)
					 {
						$("#progressbar").progressbar({
							value:100
			
						});							
					  }
			});
}

function closeLoaderDialog()
{
	$('#dialog_container').dialog('option','hide','explode').dialog('close');
}

function openMsgDialog(msg)
{
	$('#dialog_msg').html(msg).dialog({
		autoOpen: true,
		modal: true,
		show: 'fade',
		resizable: 'false',				
		buttons: { "<?php echo html_entity_decode($this->translator->translator('common_ok'), ENT_QUOTES, 'UTF-8'); ?>": function() { $(this).dialog('option', 'hide', 'explode').dialog("close"); } },
		open: function(event, ui)
			 {
				setTimeout(function() 
				{									
					if($('#' + event.target.id).dialog('isOpen'))
					{
						$('#' + event.target.id).dialog('option', 'hide', 'explode').dialog('close');										
					}
				}, 10000);
			  }
	});
}

/********************************News Tree Function*******************************************/
function categoryTreeGen()
{
	$(".example").treeTable({
	  initialState: "expanded"
	});
	
	// Drag & Drop Example Code
	$("#dnd-example .file, #dnd-example .folder").draggable({
	  helper: "clone",
	  opacity: .75,
	  refreshPositions: true,
	  revert: "invalid",
	  revertDuration: 300,
	  scroll: true
	});
	
	
	$("#dnd-example .folder").each(function() {
	  $($(this).parents("tr")[0]).droppable({
		accept: ".file, .folder",
		drop: function(e, ui) { 
		  $($(ui.draggable).parents("tr")[0]).appendBranchTo(this);
		  
		  // Issue a POST call to send the new location (this) of the 
		  // node (ui.draggable) to the server.
		  if($(ui.draggable).parents("tr")[0].id != this.id)
		  {
		  $.post("<?php echo $this->url( array('module' => 'News','controller' => 'Backend', 'action'     => 'parent' ), 'adminrout',    true) ?>", {id: $(ui.draggable).parents("tr")[0].id, to: this.id});
		  }
		},
		hoverClass: "accept",
		over: function(e, ui) {
		  if(this.id != $(ui.draggable.parents("tr.parent")[0]).id && !$(this).is(".expanded")) {
			$(this).expand();
		  }
		}
	  });
	});
	
	 $("#dnd-example .file").each(function() {
	  $($(this).parents("tr")[0]).droppable({
		accept: ".file, .folder",
		drop: function(e, ui) { 
		  $($(ui.draggable).parents("tr")[0]).appendBranchTo(this);
		  
		  // Issue a POST call to send the new location (this) of the 
		  // node (ui.draggable) to the server.
		  if($(ui.draggable).parents("tr")[0].id != this.id)
		  {
		  $.post("<?php echo $this->url( array('module' => 'News','controller' => 'Backend', 'action'     => 'parent' ), 'adminrout',    true) ?>", {id: $(ui.draggable).parents("tr")[0].id, to: this.id});
		  }
		},
		hoverClass: "accept",
		over: function(e, ui) {
		  if(this.id != $(ui.draggable.parents("tr.parent")[0]).id && !$(this).is(".expanded")) {
			$(this).expand();
		  }
		}
	  });
	});
	
	// Make visible that a row is clicked
	$("table#dnd-example tbody tr").mousedown(function() {
	  $("tr.selected").removeClass("selected"); // Deselect currently selected rows
	 $(this).addClass("selected");
	});
	
	// Make sure row is selected when span is clicked
	$("table#dnd-example tbody tr span").mousedown(function() {
		var node_id = $(this).parents("tr")[0].id.substr(5);
		var node_name = $(this).html()+' ('+node_id+')';
		if($(this).html())
		{	
			getData(node_id,'<?php echo $this->group_datas["news_sort"]; ?>','<?php echo $this->group_datas["news_order"]; ?>');
	  	}
	  $($(this).parents("tr")[0]).trigger("mousedown");
	});
}

function getData(node_id,sorts,order)
{		
		$.ajax({
			url: "<?php echo $this->url( array('module' => 'News','controller' => 'project', 'action'     => 'files' ), 'adminrout',    true) ?>",
			  	type: 'POST',
			  	data: { category_id: node_id, sort:sorts,order:order },
				beforeSend: function(){						
							openLoaderDialog();	
							removeError();			
					 },
				success: function(response){
					//alert(response);					
					var json_arr = eval("("+response+")");										
					if(json_arr.status == 'ok')
					{
						putData(json_arr.documents,node_id);															
					}					
					else
					{
						openMsgDialog(json_arr.msg);
					}
					closeLoaderDialog();
				}
		});
	
}

function deleteThis(self)
{
	var arr = $(self).attr('rel').split('_');
	$.ajax({
		 url: "<?php echo $this->url( array('module'=> 'News', 'controller' => 'backendpro', 'action'     => 'delete' ), 'adminrout',    true) ?>",
		 type: 'POST',
		 data: { id: arr[0], group_id: arr[1]},
		 beforeSend: function(){
				$(self).html('<img src="application/modules/Administrator/layouts/scripts/images/loader/ajax_loader.gif" height="16" border="0" />');
			 },
		 success: function(response) 
		 {
			//alert(response);
			var json_arr = eval("("+response+")");
			if(json_arr.status == 'ok')
			{
				$(self).parents("li:first").parents("ul:first").parents("td:first").parents("tr:first").addClass('row_selected');
				var oTables = $('#sortTable').dataTable();
				var anSelected = fnGetSelected( oTables );
				oTables.fnDeleteRow( anSelected[0] );
			}
		 }
	});
}

function sortData()
{
	$('a.sort_btn').click(function() 
	{
		var self = this;
		var rel = $(self).attr('rel');
		var rel_arr = rel.split(',');
		getData(rel_arr[0],rel_arr[1],rel_arr[2]);
	});
	
	$('a.delete_btn').click(function() {
		var self = this;
		$("#dialog-confirm").html("<?php echo addslashes($this->translator->translator('page_list_delete_confirm')); ?>").dialog({
			resizable: false,
			width: 400,
			height:180,
			modal: true,
			show: 'fade',
			hide: 'explode',
			buttons: {
					'<?php echo $this->translator->translator("common_delete_title"); ?>': function() {
					deleteThis(self);
					$(this).dialog('close');
				},
			'<?php echo html_entity_decode($this->translator->translator("common_cancel"), ENT_QUOTES, "UTF-8"); ?>': function() {
					$(this).dialog('close');
				}
			}
		});
		
	});
	
	$('a.publish_btn').click(function() {
		var self = this;
		$(self).html('<img src="application/modules/Administrator/layouts/scripts/images/loader/ajax_loader.gif" border="0" height="17" />');
		var arr = $(self).attr('rel').split('_');
		$.ajax({
			 url: "<?php echo $this->url( array('module'=> 'News', 'controller' => 'backendpro', 'action'     => 'publish' ), 'adminrout',    true) ?>",
			 type: 'POST',
			 data: { id: arr[0], page_name: arr[1], paction: arr[2]},
			 success: function(response) 
			 {
			 	//alert(response);
			 	var json_arr = eval("("+response+")");
				if(json_arr.status == 'ok')
				{
					if(json_arr.active == '1')
					{
						//$(self).parents("td:first").parents("tr:first").parents("table:first").parents("td:first").parents("tr:first").children("td:nth-child(8)").html('Published');
						$(self).html('<img src="application/modules/Administrator/layouts/scripts/images/tools/published.gif" border="0" title="<?php echo $this->translator->translator("common_unpublish_title"); ?>" alt="<?php echo $this->translator->translator("common_unpublish_title"); ?>" />').attr('rel',arr[0]+"_"+arr[1]+"_unpublish");
					}
					else
					{
						//$(self).parents("td:first").parents("tr:first").parents("table:first").parents("td:first").parents("tr:first").children("td:nth-child(8)").html('Unpublished');
						$(self).html('<img src="application/modules/Administrator/layouts/scripts/images/tools/unpublished.gif" border="0" title="<?php echo $this->translator->translator("common_publish_title"); ?>" alt="<?php echo $this->translator->translator("common_publish_title"); ?>" />').attr('rel',arr[0]+"_"+arr[1]+"_publish");
					}
			 	}
				else
				{
					openMsgDialog(json_arr.msg);
				}
			 }
		});
	});	
}

function putData(json_data,category_id)
{
	
	var tableData = '<div class="chart"><div class="data-table"><table id="sortTable" width="100%%" align="center" cellpadding="0" cellspacing="0">'+
						'<thead><tr>'+
							'<th width="4%">ID</th>'+
							'<th width="7%">Thumb </th>'+
							'<th width="24%">Document</th>'+										 
							'<th width="16%">Document Title <a href="javascript:void(0);" rel="'+category_id+',page_title,ASC" title="Ascending" class="sort_btn"><img src="application/modules/Administrator/layouts/scripts/images/tools/up-arrow.gif" border="0" /></a>&nbsp;<a href="javascript:void(0);" rel="'+category_id+',page_title,DESC" title="Descending" class="sort_btn"><img src="application/modules/Administrator/layouts/scripts/images/tools/down-arrow.gif" border="0" /></a></th>'+
							'<th width="22%">Document Desctiption </th>'+
							'<th width="13%"><?php echo $this->translator->translator("common_date"); ?>&nbsp;<a href="javascript:void(0);" rel="'+category_id+',page_date,ASC" title="Ascending" class="sort_btn"><img src="application/modules/Administrator/layouts/scripts/images/tools/up-arrow.gif" border="0" /></a>&nbsp;<a href="javascript:void(0);" rel="'+category_id+',page_date,DESC" title="Descending" class="sort_btn"><img src="application/modules/Administrator/layouts/scripts/images/tools/down-arrow.gif" border="0" /></a></th>'+
							<?php if ($this->allow('edit','backendpro','News') || $this->allow('delete','backendpro','News')) : ?>
							'<th width="27%"><?php echo $this->translator->translator("common_action"); ?></th>'+
							<?php endif; ?>	
						'</tr></thead><tbody></div></div>';
		var j = 1;
		for (var i = 0;i < json_data.length; i++)
		{ 
			if(j % 2 == 0)
			{
				var onmouseout = "this.bgColor='#FFFFFF';";
				var bgcolor = '#FFFFFF';
			}
			else
			{
				var onmouseout = "this.bgColor='#F7F7F7';";
				var bgcolor = '#F7F7F7';
			}
			
			var ext = getFileExtension(json_data[i].page_thumb);
			
			if(ext == 'jpg' || ext == 'png' || ext == 'gif' || ext == 'bmp')
			{
				var file_path = 'data/frontImages/news/page_thumb/'+json_data[i].page_thumb;
			}
			else if(ext == 'avi' || ext == 'mpeg' || ext == 'flv' || ext == 'mov' || ext == 'mp3')
			{
				var file_path = 'application/modules/Administrator/layouts/scripts/images/common/video.png';
			}
			else 
			{
				var file_path = 'application/modules/Administrator/layouts/scripts/images/common/'+ext+'.png';
			}
			var pb = (json_data[i].active == '1')? 'unpublish' : 'publish';
			var pb_img = (json_data[i].active == '1')? '<img src="application/modules/Administrator/layouts/scripts/images/tools/published.gif" border="0" title="<?php echo $this->translator->translator("common_unpublish_title"); ?>" alt="<?php echo $this->translator->translator("common_unpublish_title"); ?>" />' : '<img src="application/modules/Administrator/layouts/scripts/images/tools/unpublished.gif" border="0" title="<?php echo $this->translator->translator("common_publish_title"); ?>" alt="<?php echo $this->translator->translator("common_publish_title"); ?>" />';
			tableData += '<tr  bgcolor="'+bgcolor+'" onmouseover="this.bgColor=\'#FCF5DD\';" onmouseout="'+onmouseout+'">'+										 
										  '<td class="center">'+json_data[i].id+'</td>'+	
										  '<td class="center"><span class="thumb"><img src="'+file_path+'" width="20" height="20" /></span></td>'+	
										  '<td><a href="data/frontImages/news/page_thumb/'+json_data[i].page_thumb+'" >'+json_data[i].page_thumb+'</a></td>'+										  
										  '<td title="'+json_data[i].page_title+'">'+json_data[i].page_name+'</td>'+	
										  '<td>'+json_data[i].page_desc+'</td>'+	
										  '<td class="center">'+json_data[i].page_date+'</td>'+	
										  <?php if ($this->allow('edit','backendpro','News') || $this->allow('delete','backendpro','News')) : ?>									  
										  '<td  class="tools-list">'+	
											 '<ul>'+
												'<li>'+	
													<?php if ($this->allow('edit','backendpro','News')) : ?>
														'<a href="<?php echo $this->url( array("module"=> "News", "controller" => "backendpro", "action"     => "edit", "id" => "" ), "adminrout",    true) ?>'+json_data[i].id+'"><img src="application/modules/Administrator/layouts/scripts/images/tools/edit.png" title="<?php echo $this->translator->translator("common_edit_title"); ?>" alt="<?php echo $this->translator->translator("common_edit_title"); ?>" border="0" /></a>'+
													<?php  endif; ?>
												'</li>'+
												'<li>'+
														<?php if ($this->allow('delete','backendpro','News')) : ?>
														'<a href="javascript:void(0);" class="delete_btn"  rel="'+json_data[i].id+'_'+json_data[i].group_id+'"><img src="application/modules/Administrator/layouts/scripts/images/tools/delete.png" title="<?php echo $this->translator->translator("common_delete_title"); ?>" alt="<?php echo $this->translator->translator("common_delete_title"); ?>" border="0" /></a>'+
														<?php endif; ?>
												 '</li>'+
												 '<li>'+
														<?php if ($this->allow('publish','backendpro','News')) : ?>
														'<a href="javascript:void(0);" class="publish_btn" rel="'+json_data[i].id+'_'+json_data[i].page_name+'_'+pb+'">'+pb_img+'</a>'+
														<?php endif; ?>	
												 '</li>'+						 
											 '</ul>'+
										  '</td>'+
										  <?php endif; ?>
										'</tr>';
			j++;								
		}
		tableData += '</tbody></table>';
		$('#putContent').html(tableData);
		
		
		/****************************Sorting Table Start*********************/
		oTable = $("#sortTable").dataTable({
				"bPaginate": true,
				"aLengthMenu" : [ 1, 10, 25, 50, 100 ],
				"bDestroy":true,
				"bLengthChange": true,
				"bSearchable": true,
				"bFilter": true,
				"bSort": true,
				"bInfo": true,
				"sPaginationType": "full_numbers",
				"bAutoWidth": true,
				"bProcessing": false,
				"bSortClasses": true,
				"bStateSave": false,
				"bServerSide": false,
				"aaSorting": [[ 2, "asc" ]],				
				"aoColumnDefs": [ 
						{ "bSortable": false, "bSortClasses": false,  "aTargets": [ 0 ] }
					],
				"oLanguage" : { "sSearch": "<?php echo $this->translator->translator('jquery_filter'); ?>" }
			});	
		
		$('td', oTable.fnGetNodes()).hover( function() {		
			$(this).parents("tr:first").children('td').addClass( 'highlighted' );
		}, function() {
			$('td.highlighted').removeClass('highlighted');
		} );
		
		var oSettings = oTable.fnSettings();
		var len = oSettings._iDisplayLength;
		i--;
		var totalPage = i/len;
		totalPage = Math.ceil(totalPage);
		for(var j = totalPage; j > 0; j-- )
		{
			oTable.fnPageChange( 'next' );			
			sortData();
			imageThumbnil();
		}
		oTable.fnPageChange( 'first' );	
		sortData();
		imageThumbnil();
		
		/* Get the rows which are currently selected */
		function fnGetSelected( oTableLocal )
		{
			var aReturn = new Array();
			var aTrs = oTableLocal.fnGetNodes();
			
			for ( var i=0 ; i<aTrs.length ; i++ )
			{
				if ( $(aTrs[i]).hasClass('row_selected') )
				{
					aReturn.push( aTrs[i] );
				}
			}
			return aReturn;
		}
		/****************************Sorting Table End*********************/
}

function getFileExtension(filename)
{
	return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
}
	
/********************************Refresh News Tree*******************************************/
function refreshCategoryTree()
{
	var group_id = $('#group_id').val();
	var category_parent = $('#category_parent').val();
	if(group_id != '')
	{
		$.ajax({
			url: "<?php echo $this->url( array('module' => 'News','controller' => 'Backend', 'action'     => 'categorytree' ), 'adminrout',    true) ?>",
			type: 'POST',
			data: { grp_id: group_id, parent : category_parent },
			success: function(response){				
				var json_arr = eval("("+response+")");
				if(json_arr.status == 'ok')
				{
					var tree = '<table class="example" id="dnd-example">'+
									'<tbody ><tr id="node-0">'+
									 '<td>'+
										'<span class="folder"><?php echo $this->translator->translator("common_root"); ?></span>'+
									'</td>'+
								'</tr>';
						tree += json_arr.categoryTree+'</tbody></table>';
					$('#categoryTree').html(tree);
					categoryTreeGen();
				}
				else
				{
					var tree = '<table class="example" id="dnd-example">'+
										'<tbody ><tr id="node-0">'+
										 '<td>'+
											'<span class="folder"><?php echo $this->translator->translator("common_root"); ?></span>'+
										'</td>'+
									'</tr>';
							tree += '</tbody></table>';
					$('#categoryTree').html(tree);
					categoryTreeGen();
				}					
			}
		});
	}
	else
	{
		var tree = '<table class="example" id="dnd-example">'+
										'<tbody ><tr id="node-0">'+
										 '<td>'+
											'<span class="folder"><?php echo $this->translator->translator("common_root"); ?></span>'+
										'</td>'+
									'</tr>';
							tree += '</tbody></table>';
		$('#categoryTree').html(tree);
		categoryTreeGen();			
	}	
}

/************************************************IMAGE THUMBNIL************************************************/
function imageThumbnil()
{	
	$("span.thumb").hover(function() {
		$(this).css({'z-index' : '10'}); /*Add a higher z-index value so this image stays on top*/ 
		$(this).find('img').addClass("hover").stop() /* Add class of "hover", then stop animation queue buildup*/
			.animate({
				marginTop: '-110px', /* The next 4 lines will vertically align this image */ 
				marginLeft: '-110px',
				top: '50%',
				left: '50%',
				width: '174px', /* Set new width */
				height: '174px', /* Set new height */
				padding: '20px'
			}, 200); /* this value of "200" is the speed of how fast/slow this hover animates */
	
		} , function() {
		$(this).css({'z-index' : '0'}); /* Set z-index back to 0 */
		$(this).find('img').removeClass("hover").stop()  /* Remove the "hover" class , then stop animation queue buildup*/
			.animate({
				marginTop: '-4', /* Set alignment back to default */
				marginLeft: '0',
				top: '0',
				left: '0',
				width: '30px', /* Set width back to default */
				height: '20px', /* Set height back to default */
				padding: '5px'
			}, 400);
	});
}
</script>

<div id="container">
<div class="title-container">
	<div class="project"><h1><?php echo $this->translator->translator('news_frontend_project_list'); ?></h1></div>
</div>

<div class="content-container">
	<div id="sidebar-inner">
    	<div id="nav">
    		<div class="nav-header"><div class="nav-title"><?php echo $this->translator->translator('news_frontend_project_tree'); ?></div></div>
    		<div id="categoryTree" class="nav-body treebody" >
           		<?php echo $this->categoryTree; ?>
            </div>
       	</div>
    </div>
    	
    <div id="content-inner">
    	<div id="actionMessage"></div>
        <div id="putContent"></div>
	</div>
</div>

<div id="dialog_msg" title="Message......"></div>
<div id="dialog-confirm" title="Delete Confirmation"></div>
<div id="dialog_container" style="display:none" title="Please Wait For Processing...">
	<div id="progressbar" ></div>	
</div>
</div>